/**
 *  获取路由信息
 *    统一处理信息格式化
 * 
 **/
import { useRouter, RouteRecordRaw } from 'vue-router'
import { ComputedRef, computed } from 'vue'
import tools from '@src/utils/tools.js'
const { getUid } = tools
const user = {
    roles: ['admin', 'user'] // 用户角色
}

// 路由过滤函数
function filterRoutesByRoles(routes: RouteRecordRaw[], userRoles: string[]): RouteRecordRaw[] {
  return routes.filter(route => {
    const routeRoles = route.meta?.roles || []
    if (routeRoles.includes('*') || !routeRoles.length) {
      return true // 如果路由对所有角色开放或者没有指定角色，则直接返回 true
    }
    return routeRoles.some(role => userRoles.includes(role))
  })
}

function filterChildRoutes(routes: RouteRecordRaw[]): RouteRecordRaw {
  return routes
    .filter(route => route.meta?.show || route.meta?.show === undefined)
    .map(route => (
      { name: route.name || '',
        title: '456',
        // title: route.meta?.title ?? (route.meta.title || '未命名'),
        id: getUid(), path: route.path,
        meta: route.meta, 
        children: route.children ? filterChildRoutes(route.children) : [] 
      }))
    .sort((a, b) => {
      const slotA = a.meta?.slot ?? Infinity
      const slotB = b.meta?.slot ?? Infinity
      return slotA - slotB
    })
}

function getMenu(routes: RouteRecordRaw[]): RouteRecordRaw {

  /**
   * 过滤页面
   *   404
   **/   
  const filterPaths = ['/:pathMatch(.*)*']
  const filteredRoutes = routes.filter(route => !filterPaths.includes(route.path))
  const topLevelRoutes = filteredRoutes
    .filter(route => route.meta?.show)
    .map(route => ({
      meta: route.meta,
      // title: '123',
      title: route.meta?.title ?? route.meta.title,
      name: route?.name ?? route.name,
      path: route.path,
      id: getUid(),
      children: route.children ? filterChildRoutes(route.children) : []
    }))
  return topLevelRoutes.sort((a, b) => {
      const slotA = a.meta?.slot ?? Infinity
      const slotB = b.meta?.slot ?? Infinity
      return slotA - slotB
  })
}

// 构建最终菜单结构
export function useMenu(): ComputedRef<RouteRecordRaw[]> {
    const router = useRouter()
    const allRouterRoutes = router.getRoutes()
    const finalMenu = computed(() => {
      const filteredRoutes = filterRoutesByRoles(allRouterRoutes, user.roles)
      return getMenu(filteredRoutes)
    })
    console.log('最终菜单', finalMenu)
    return finalMenu
}